<template>
  <div class="">
    <el-tabs
      v-model="currentSlaveId"
      type="card"
      class="tabs"
      :before-leave="beforeLeave"
      @tab-remove="removeTab"
      @tab-click="handleClick"
    >
      <el-tab-pane
        v-for="tab in tabs"
        :key="tab.id"
        :label="tab.title"
        :name="tab.id"
        :closable="true"
      >
        <RegisterView
          v-if="tab.id == currentSlaveId"
          :deviceName="routeName"
          :slaveId="currentSlaveId"
        />
      </el-tab-pane>
      <!-- 添加从站 -->
      <el-tab-pane name="add" :closable="false">
        <template #label>
          <el-icon>
            <Plus/>
          </el-icon>
          增加从机
        </template>
      </el-tab-pane>
      <AddSlave
        :deviceName="routeName"
        :dialogVisible="dialogVisible"
        :setDialogVisible="setDialogVisible"
        @addSuccess="addSuccess"
      />
    </el-tabs>
  </div>
</template>

<script lang="ts" setup name="Slave">
import {ref, watch, type PropType, computed} from "vue";
import {useRoute} from "vue-router";
import {ElMessage, ElMessageBox, type TabsPaneContext} from "element-plus";
import type {Device} from "@/types/device.ts";
import RegisterView from "./RegisterView.vue";
import {deleteSlave, getSlaveIdList} from "@/api/slaveApi.ts";
import {Plus} from '@element-plus/icons-vue';
import AddSlave from "./AddSlave.vue";

const route = useRoute();
const routeName = ref(route.name as string);
const slaveIdList = ref<number[]>([]);
const currentSlaveId = ref(1);
const dialogVisible = ref(false);

let props = defineProps({
  device: {
    type: Object as PropType<Device>,
    required: true,
  },
});

const setDialogVisible = (value: boolean) => {
  dialogVisible.value = value;
}

const addSuccess = async (slaveId: number) => {
  setDialogVisible(false);
  slaveIdList.value = await getSlaveIdList(props.device.name);
  currentSlaveId.value = tabs.value[tabs.value.length - 1].id;
  ElMessage({
    type: "success",
    message: `从机${slaveId}增加成功!`,
    duration: 3000,
  });
};

const tabs = computed(() => {
  return slaveIdList.value.map((slaveId) => {
    return {
      title: `从机${slaveId}`,
      id: slaveId,
    };
  });
});

const beforeLeave = (activeName: string) => {
  if (activeName === 'add') {
    addTab();
    return false; // 阻止切换
  }
  return true;
};

const addTab = () => {
  setDialogVisible(true);
};

const removeTab = async (slaveId: number) => {
  await ElMessageBox.confirm(
    `确定要删除从机 ${slaveId} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  );
  const isSuccess = await deleteSlave(routeName.value, slaveId);
  if (isSuccess) {
    ElMessage({
      type: "success",
      message: `从机${slaveId}删除成功!`,
      duration: 3000,
    });
    slaveIdList.value = await getSlaveIdList(routeName.value);
  } else {
    ElMessage({
      type: "error",
      message: `从机${slaveId}删除失败!`,
      duration: 3000,
    });
  }
};

// 封装数据获取逻辑
const fetchSlaveList = async () => {
  // 如果 device 存在
  if (props.device) {
    slaveIdList.value = await getSlaveIdList(props.device.name);
  }
  if (slaveIdList.value.length > 0) {
    currentSlaveId.value = slaveIdList.value[0]; // 设置默认激活的 Tab
  }
};

const handleClick = (tab: TabsPaneContext) => {
  if (tab.index !== undefined) {
    const index = parseInt(tab.index);
    if (index >= 0 && index < slaveIdList.value.length) {
      currentSlaveId.value = slaveIdList.value[index];
    }
  }
};

watch(
  () => route.name,
  async (newName) => {
    if (newName) {
      routeName.value = newName as string;
    }
  }
);

// 监听设备名称的变化
watch(
  () => props.device,
  async (newDevice) => {
    if (newDevice) {
      await fetchSlaveList();
    }
  }
);
</script>

<style scoped>
.tabs {
  margin-top: 20px;
  margin-left: 20px;
  margin-bottom: 0px;
}

/* 标签栏容器 */
:deep(.el-tabs__nav-wrap) {
  position: relative;
  padding-right: 0 !important;
  overflow: visible !important; /* 防止裁剪 */
}

/* 标签列表 */
:deep(.el-tabs__nav) {
  display: inline-flex;
  flex-wrap: nowrap;
}

/* 新增按钮 */
:deep(.el-tabs__new-tab) {
  position: relative !important;
  display: inline-flex !important;
  align-items: center;
  margin: 0 0 0 4px !important;
  border-radius: 0 4px 4px 0;
  border-left: 1px solid var(--el-border-color-light);
}
</style>
